// pages/member/personInfo/index.js
import { update } from '../../../api/user'
import { getInfo } from '../../../api/member'
import {
  policy
} from '../../../api/oss'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar:'',
    haveAvatar:false,
    nickname:'',
    userInfo: {},
    title: '迷失的阿斌',
    dataObj: {
      policy: '',
      signature: '',
      key: '',
      ossaccessKeyId: '',
      dir: '',
      host: ''
    },
    host: "",
    images:''
  },
  dialogClick() {
    this.selectComponent('#dialog').appear()
  },
  
  getUserInfo: function (e) {
    console.log("用户信息授权的数据e--"+JSON.stringify(e))
    let sendData = {}
    sendData.avatar = e.detail.userInfo.avatarUrl
    sendData.nickname = e.detail.userInfo.nickName
    
    update(sendData).then(
            res => {
                    console.log("接收用户信息--" + JSON.stringify(res))
                    if (res.type == 'success') {
                            this.setData({
                                    haveAvatar: true,
                                    avatar: res.data.avatar,
                                    nickname: res.data.nickname,
                            })
                    }
            }
    ).catch(error => {
            console.log(error)
    })
},
   // 检查头像的授权状态
   checkAuthorize() {
    console.info("我进检查了")
    let userInfo = app.globalData.userInfo

    if (userInfo.hasOwnProperty("nickname")){
         this.setData({
                 nickname: app.globalData.userInfo.nickname
         })  
    }
    if (userInfo.hasOwnProperty("avatar")){
         this.setData({
                 haveAvatar: true,
                 avatar: app.globalData.userInfo.avatar,
         })  
    }
},
  choseImage() {
    var _this = this
    _this.beforeUpload()
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var tempFilePath = res.tempFilePaths
        _this.uploadImg(tempFilePath)
        // update({
        //   avatar:res.tempFilePaths[0]
        //  }).then(res=>{
        //     app.globalData.userInfo.avatar=res.data.avatar
        //     _this.data.userInfo.avatar=res.data.avatar
        //     _this.setData({
        //       userInfo: _this.data.userInfo
        //     })
        //  })
      }
    })
  },
  savedialogClick(e) {
    update({
      nickname: e.detail
    }).then(res => {
      app.globalData.userInfo.nickname = res.data.nickname
      this.data.userInfo.nickname = res.data.nickname
      this.setData({
        userInfo: this.data.userInfo
      })
    })
    this.setData({
      title: this.data.title
    })
  },

  beforeUpload(file) {
    let _self = this;
    policy().then(response => {
      _self.data.dataObj.policy = response.data.policy;
      _self.data.dataObj.signature = response.data.signature;
      _self.data.dataObj.ossaccessKeyId = response.data.accessKeyId;
      _self.data.dataObj.dir = response.data.dir;
      _self.data.dataObj.key = response.data.dir + "/${filename}";
      _self.data.dataObj.host = response.data.action;
      _self.data.host = response.data.host
    }).catch(err => {
      wx.showToast({
        icon: "none",
        title: err.content,
      })
    })
  },
  // 上传图片
  uploadImg(filePath) {
    let _this = this;
    _this.setData({
      uploadPercent: true
    })
    let {
      host,
      ossaccessKeyId,
      policy,
      signature
    } = this.data.dataObj;
    let imgList = [];
    filePath.map((item) => {
      wx.uploadFile({
        url: host,
        filePath: item,
        name: 'file',
        formData: _this.data.dataObj,
        success: res => {
          console.log(res)
          if (res.statusCode === 200 || res.statusCode === 204) {
            _this.setData({
              uploadPercent: false
            });
            var fileName = ''
            if (item.indexOf("http://tmp/") != -1) {
              fileName = item.split('http://tmp/')[1];
            } else if (item.indexOf("wxfile://") != -1) {
              fileName = item.split('wxfile://')[1];
            }
            console.log(item)
            _this.data.images=_this.data.host + '/' + _this.data.dataObj.dir + '/' + fileName;
            update({
              avatar: _this.data.images
            }).then(res => {
              app.globalData.userInfo.avatar = res.data.avatar
              _this.data.userInfo.avatar = res.data.avatar
              _this.setData({
                userInfo: _this.data.userInfo
              })
            })
          }
        },
        fail: res => {
          wx.showToast({
            icon: "none",
            title: res.content,
          })
        }
      })
    });
  },
  loginClick(){
    wx.navigateTo({
      url: '/pages/login/index',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onShow: function () {
    this.checkAuthorize()
  },

})
